package cn.usian.jyzx.pay.service.impl;

import cn.usian.jyzx.model.entity.order.OrderInfo;
import cn.usian.jyzx.pay.config.MessageQueueHelper;
import cn.usian.jyzx.pay.fegin.OrderFegin;
import cn.usian.jyzx.pay.service.AliPayService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @TODO:
 * @Author:baimu
 * @Date:2024 11 11 14 05
 **/

@Service
@Slf4j
public class AliPayServiceImpl implements AliPayService {

    @Autowired
    MessageQueueHelper messageQueueHelper;


    @Autowired
    OrderFegin orderFegin;

    /**
     * 沙箱环境：测试环境 https://open.alipay.com/develop/sandbox/account
     *
     * @param orderNo
     * @throws AlipayApiException
     */
    @Override
    public String submitAlipay(String orderNo) throws AlipayApiException {

        log.info("submitAlipay(String orderNo):{}", orderNo);

        OrderInfo orderInfo = orderFegin.getOrderInfo(orderNo);
        //对接支付宝支付

        //应用私钥
        String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCbfyVsiO83cesTtQsMNqnm1tKP9jT1rFFbGfmwq7C/h7GiEkgMaFLC1BTqftDLGm6inFk2Pmm2OyZUY/sEIAjh6WTJF7q0lz+yQX2wKsbT6HhFiZs7UHkTCQCJLwHZGC+CjsQuaAHEa9sgrmovlV2P86lKu6/IBvxjKpWQN+rdHPOTSgKCpmQZ164JbUF7PbRvEYGzEiwauNIu7suPtxAZdDS+Dw2BSSPcubIP38DNAq8lbngJkRRo+ZoYTYOQAVr++5HjAsHTqk0pHcz5tBuGd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RQpVOMGce+p3otyTsgbQ5zbOcFP9wzIqgZ4lFYfpLBAoGAQAKiOCg2zfjwgcTuTf85FzcdZhqbJ9ZFBU+gnXPbpfPBUEV9Sn7hXiaFYQYkQD5X82uZWz0ctwgIY6cGJsZnx7UvJLIzBw1jwJ76KqiBbyjfhgMxRuQDvJ3N8JNE7ydtarH1x6250M3uZU6jEANXzt+7SzxYwh9r1nz8/IPg2Vc=";
        //支付宝公钥:
        String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqsVebyF+31stH4xkMeTPpwszLtPMMWw1dWfKLEWiC7khwGFaW+rEjoIdL8es/YJGTr2JdybmIPbqMtUwty33kCTJx2vAQqd+1iOEVc/s1S6i/a/P2Jvqf2vet87jlbsBv2I7TrjexxF9rVNGhraJKQr9gfH8W6jzsJDTVyiz9MtxGXYcYoR077zC/aIZBXrft3xG+ZyARHo2fu4HaU+q//OkQP9WvtWDulr2Q3oJPjs2k8cnJFAo3m/D/FOCSinH96G4Y5KwXxBMnzh1ne+EF6ZftY6DQgTjgxuY8Lf3imcXXzjy8oFGYxUxC68zURKQZExSiGDPXKFOpCytluZ8kwIDAQAB";
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");
        alipayConfig.setAppId("9021000132690996");
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");

        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(orderNo);
        model.setTotalAmount(String.valueOf(orderInfo.getTotalAmount()));
        model.setSubject("积云甄选");
        model.setProductCode("QUICK_WAP_WAY");

        //model.setSellerId("2088102147948060");
        request.setBizModel(model);
        //HTTP/HTTPS开头字符串
        request.setReturnUrl("http://localhost:8086/api/order/alipay/returnAlipay");
        //支付宝服务器主动通知商户服务器里指定的页面http/https路径。
        request.setNotifyUrl("http://localhost:8086/api/order/alipay/notifyAlipay");
        AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "POST");
        // 如果需要返回GET请求，请使用
        // AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "GET");
        String pageRedirectionData = response.getBody();
        log.info("pageRedirectionData:{}", pageRedirectionData);


        if (response.isSuccess()) {
            log.info("调用成功");

        } else {
            log.info("调用失败");

            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }

        return pageRedirectionData;

    }

    @Override
    public String returnPay(String out_trade_no) {
        return null;
    }

    @Override
    public String notifyPay(Map<String, String> params) throws AlipayApiException {

      //调用SDK验证签名
      //公钥验签示例代码
        String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqsVebyF+31stH4xkMeTPpwszLtPMMWw1dWfKLEWiC7khwGFaW+rEjoIdL8es/YJGTr2JdybmIPbqMtUwty33kCTJx2vAQqd+1iOEVc/s1S6i/a/P2Jvqf2vet87jlbsBv2I7TrjexxF9rVNGhraJKQr9gfH8W6jzsJDTVyiz9MtxGXYcYoR077zC/aIZBXrft3xG+ZyARHo2fu4HaU+q//OkQP9WvtWDulr2Q3oJPjs2k8cnJFAo3m/D/FOCSinH96G4Y5KwXxBMnzh1ne+EF6ZftY6DQgTjgxuY8Lf3imcXXzjy8oFGYxUxC68zURKQZExSiGDPXKFOpCytluZ8kwIDAQAB";
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, "UTF-8", "RSA2");
      //公钥证书验签示例代码
      //   boolean flag = AlipaySignature.rsaCertCheckV1(params,alipayPublicCertPath,"UTF-8","RSA2");

        if (signVerified) {
            String outTradeNo = params.get("out_trade_no");
            messageQueueHelper.sendMessage("order-pay-exchange","order-pay-queue","pay",outTradeNo);


            // TODO 验签成功后
            //按照支付结果异步通知中的描述，对支付结果中的业务内容进行1\2\3\4二次校验，校验成功后在response中返回success
            String tradeStatus = params.get("trade_status");
            if (tradeStatus.equals("TRADE_SUCCESS") || tradeStatus.equals("TRADE_FINISHED")) {

                //String outTradeNo = params.get("out_trade_no");
                OrderInfo orderInfo = orderFegin.getOrderInfo(outTradeNo);
                if(null==orderInfo){
                    log.info("订单不存在:{}",outTradeNo);
                    return "error";
                }
                //
                //
                //      修改订单状态  消息队列


                //int i = orderFegin.updateOrderStatus(outTradeNo, 1);
                //rabbitTemplate.convertAndSend("order-event-exchange","order.pay",outTradeNo);

                messageQueueHelper.sendMessage("order-pay-exchange","order-pay-queue","pay",outTradeNo);
//                if(i==0){
//                    log.info("订单状态修改失败:{}",outTradeNo);
//                    return "error";
//                }else{
//                    return "success";
//                }
                return "success";



            }


        } else {
            // TODO 验签失败则记录异常日志，并在response中返回fail.
            log.info("验签失败");
        }
        return null;
    }
}
